import api from '../../../services/api'
import {defineStore} from "pinia";
import {Activity, Pagination, Sorting} from "../types";

const activityList = async (options: Partial<Sorting> & Pagination) => {
  try {
    const res = await api.post('/admin/lottery/activity/page', {
      "pageNumber": 0,
      "pageSize": 10
    })
    return {
      data: res.data.data.content,
      pagination: {
        page: res.data.data.pageable.pageNumber,
        perPage: options.perPage,
        total: res.data.data.totalElements,
      },
    }
  } catch (err) {
    console.error(err);
  }
  return {
    data: [],
    pagination: {
      page: 0,
      perPage: 0,
      total: 0,
    },
  };
};

const createActivity = async (activity: Activity) => {
  try {
    const res = await api.post('/admin/lottery/activity/create', activity)
    return res.data.data;
  } catch (err) {
    console.error(err);
  }
  return null;
};

const recruiting = async (activityId: number | undefined) => {
  try {
    const res = await api.get('/admin/lottery/activity/recruiting?id=' + activityId, {
    })
    return res.data.data;
  } catch (err) {
    console.error(err);
  }
  return null;
}

const activeActivity = async (activityId: number | undefined) => {
  try {
    const res = await api.get('/admin/lottery/activity/active?id=' + activityId, {
    })
    return res.data.data;
  } catch (err) {
    console.error(err);
  }
  return null;
}

export const useActivityStore = defineStore('activity', {
  state: () => {
    return {
      items: [] as Activity[],
      pagination: {
        page: 1,
        perPage: 10,
        total: 0,
      } as Pagination,
    }
  },

  actions: {
    async getPage(options: {  sorting?: Sorting; pagination: Pagination }) {
      const { data, pagination } = await activityList({
        ...options.sorting,
        ...options.pagination,
      })
      this.items = data
      this.pagination = pagination
    },
     createActivity: async (activity: Activity) => {
      const res = await createActivity(activity);
       console.log(res)
    },
    recruiting: async (activityId: number | undefined)=>  {
      const res = await recruiting(activityId);
      console.log(res)
    },
    activeActivity: async (activityId: number | undefined)=>  {
      const res = await activeActivity(activityId);
      console.log(res)
    },
  }
});
